<template>
  <Dialog v-model="dialogVisible" title="配置" width="1000px">
    <h5>大类配置</h5>
    <el-table border class="tables" :data="configList" row-key="id">
      <el-table-column prop="columnName" label="技术类型">
        <template #default="scope">
          {{ getName(scope.row.columnName) }}
        </template>
      </el-table-column>
      <el-table-column label="是否校验" align="center" prop="columnCheckFlag">
        <template #default="scope">
          <el-checkbox
            v-model="scope.row.columnCheckFlag"
            @change="handleChecked(scope.row.columnCheckFlag, scope.column.property, scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="校验规则" align="center" prop="rule">
        <template #default="scope">
          <el-radio-group
            v-if="scope.row.columnName == 'sex'"
            v-model="scope.row.columnValue"
            @change="handleChecked(scope.row.columnValue, scope.column.property, scope.row)"
            :disabled="!scope.row.columnCheckFlag"
          >
            <el-radio value="1">男</el-radio>
            <el-radio value="2">女</el-radio>
          </el-radio-group>
          <el-radio-group
            v-if="scope.row.columnName == 'isAutoAuth'"
            v-model="scope.row.columnValue"
            @change="handleChecked(scope.row.columnValue, scope.column.property, scope.row)"
            :disabled="!scope.row.columnCheckFlag"
          >
            <el-radio value="1">是</el-radio>
            <el-radio value="0">否</el-radio>
          </el-radio-group>
          <el-tree-select
            v-if="scope.row.columnName == 'departId'"
            v-model="scope.row.columnValue"
            multiple
            :data="departList"
            check-strictly="true"
            :render-after-expand="false"
            @change="handleChecked(scope.row.columnValue, scope.column.property, scope.row)"
            :disabled="!scope.row.columnCheckFlag"
          />
          <el-tree-select
            v-if="scope.row.columnName == 'bizDepartId'"
            v-model="scope.row.columnValue"
            multiple
            :data="departList1"
            check-strictly="true"
            :render-after-expand="false"
            @change="handleChecked(scope.row.columnValue, scope.column.property, scope.row)"
            :disabled="!scope.row.columnCheckFlag"
          />
          <el-select
            v-if="scope.row.columnName == 'roleId'"
            v-model="scope.row.columnValue"
            multiple
            @change="handleChecked(scope.row.columnValue, scope.column.property, scope.row)"
            :disabled="!scope.row.columnCheckFlag"
          >
            <el-option v-for="item in roleList" :key="item.id" :label="item.name" :value="item.id"
          /></el-select>
          <el-select
            v-if="scope.row.columnName == 'postId'"
            v-model="scope.row.columnValue"
            multiple
            @change="handleChecked(scope.row.columnValue, scope.column.property, scope.row)"
            :disabled="!scope.row.columnCheckFlag"
          >
            <el-option v-for="item in postList" :key="item.id" :label="item.name" :value="item.id"
          /></el-select>
          <el-select
            v-if="scope.row.columnName == 'dutyId'"
            v-model="scope.row.columnValue"
            multiple
            @change="handleChecked(scope.row.columnValue, scope.column.property, scope.row)"
            :disabled="!scope.row.columnCheckFlag"
          >
            <el-option v-for="item in dutyList" :key="item.id" :label="item.name" :value="item.id"
          /></el-select>
          <el-select
            v-if="scope.row.columnName == 'workGroupId'"
            v-model="scope.row.columnValue"
            multiple
            @change="handleChecked(scope.row.columnValue, scope.column.property, scope.row)"
            :disabled="!scope.row.columnCheckFlag"
          >
            <el-option
              v-for="item in workGroupList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
          /></el-select>
          <el-select
            v-if="scope.row.columnName == 'whiteList'"
            v-model="scope.row.columnValue"
            multiple
            @change="handleChecked(scope.row.columnValue, scope.column.property, scope.row)"
            :disabled="!scope.row.columnCheckFlag"
          >
            <el-option v-for="item in whiteList" :key="item.id" :label="item.name" :value="item.id"
          /></el-select>
        </template>
      </el-table-column>
    </el-table>
    <div class="flex items-center">
      <h5>单个技术配置</h5>
      <el-switch v-model="showSingle" class="ml-2" style="--el-switch-on-color: #13ce66"
    /></div>
    <div class="flex" v-if="showSingle">
      <div class="left" style="width: 240px">
        <el-input
          v-model="search"
          @change="getTechList(search)"
          style="width: 240px"
          placeholder="请搜索"
        />
        <div style="width: 240px" class="techList">
          <div
            class="h-8 leading-8 p-l-2 item"
            :class="{ active: tech.id == selectId }"
            v-for="tech in techList"
            :key="tech.id"
            @click="handleRule(tech.id)"
            >{{ tech.name }}</div
          >
        </div>
      </div>
      <div class="right flex-1">
        <el-table border class="tables w-full" :data="itemConfigList" row-key="id">
          <el-table-column prop="columnName" label="技术类型">
            <template #default="scope">
              {{ getName(scope.row.columnName) }}
            </template>
          </el-table-column>
          <el-table-column label="是否校验" align="center" prop="columnCheckFlag">
            <template #default="scope">
              <el-checkbox
                v-model="scope.row.columnCheckFlag"
                @change="
                  handleChecked1(scope.row.columnCheckFlag, scope.column.property, scope.row)
                "
              />
            </template>
          </el-table-column>
          <el-table-column label="校验规则" align="center" prop="rule">
            <template #default="scope">
              <el-radio-group
                v-if="scope.row.columnName == 'sex'"
                v-model="scope.row.columnValue"
                @change="handleChecked1(scope.row.columnValue, scope.column.property, scope.row)"
                :disabled="!scope.row.columnCheckFlag"
              >
                <el-radio value="1">男</el-radio>
                <el-radio value="2">女</el-radio>
              </el-radio-group>
              <el-radio-group
                v-if="scope.row.columnName == 'isAutoAuth'"
                v-model="scope.row.columnValue"
                @change="handleChecked1(scope.row.columnValue, scope.column.property, scope.row)"
                :disabled="!scope.row.columnCheckFlag"
              >
                <el-radio value="1">是</el-radio>
                <el-radio value="0">否</el-radio>
              </el-radio-group>
              <el-tree-select
                v-if="scope.row.columnName == 'departId'"
                v-model="scope.row.columnValue"
                multiple
                check-strictly="true"
                :data="departList"
                :render-after-expand="false"
                @change="handleChecked1(scope.row.columnValue, scope.column.property, scope.row)"
                :disabled="!scope.row.columnCheckFlag"
              />
              <el-tree-select
                v-if="scope.row.columnName == 'bizDepartId'"
                v-model="scope.row.columnValue"
                multiple
                check-strictly="true"
                :data="departList1"
                :render-after-expand="false"
                @change="handleChecked1(scope.row.columnValue, scope.column.property, scope.row)"
                :disabled="!scope.row.columnCheckFlag"
              />
              <el-select
                v-if="scope.row.columnName == 'roleId'"
                v-model="scope.row.columnValue"
                multiple
                @change="handleChecked1(scope.row.columnValue, scope.column.property, scope.row)"
                :disabled="!scope.row.columnCheckFlag"
              >
                <el-option
                  v-for="item in roleList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
              /></el-select>
              <el-select
                v-if="scope.row.columnName == 'postId'"
                v-model="scope.row.columnValue"
                multiple
                @change="handleChecked1(scope.row.columnValue, scope.column.property, scope.row)"
                :disabled="!scope.row.columnCheckFlag"
              >
                <el-option
                  v-for="item in postList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
              /></el-select>
              <el-select
                v-if="scope.row.columnName == 'dutyId'"
                v-model="scope.row.columnValue"
                multiple
                @change="handleChecked1(scope.row.columnValue, scope.column.property, scope.row)"
                :disabled="!scope.row.columnCheckFlag"
              >
                <el-option
                  v-for="item in dutyList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
              /></el-select>
              <el-select
                v-if="scope.row.columnName == 'workGroupId'"
                v-model="scope.row.columnValue"
                multiple
                @change="handleChecked1(scope.row.columnValue, scope.column.property, scope.row)"
                :disabled="!scope.row.columnCheckFlag"
              >
                <el-option
                  v-for="item in workGroupList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
              /></el-select>
              <el-select
                v-if="scope.row.columnName == 'whiteList'"
                v-model="scope.row.columnValue"
                multiple
                @change="handleChecked1(scope.row.columnValue, scope.column.property, scope.row)"
                :disabled="!scope.row.columnCheckFlag"
              >
                <el-option
                  v-for="item in whiteList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
              /></el-select>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <template #footer>
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import * as Api from '@/api/qualification/index'
import { cloneDeep } from 'lodash-es'
import * as DeptApi from '@/api/system/dept'
import * as RoleApi from '@/api/system/role'
import * as PostApi from '@/api/system/post'
import * as UserApi from '@/api/system/user'
import { handleTree } from '@/utils/tree'
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const configList = ref([])
const itemConfigList = ref([])
const techList: any = ref([])
const search = ref('')
const parentId = ref('')
const showSingle = ref(false)

const departList = ref([])
const departList1 = ref([])
const roleList: any = ref([])
const postList: any = ref([])
const dutyList: any = ref([])
const workGroupList: any = ref([])
const whiteList: any = ref([])

let newBasicId = ''
let newTechId = ''
let selectId = ref('')

const getGroupListTrees = (data: any) => {
  if (Array.isArray(data)) {
    return data.map((item) => getGroupListTrees(item))
  } else if (typeof data === 'object' && data !== null) {
    const result: any = {}
    for (let key in data) {
      if (key === 'name') {
        result.label = data[key]
      } else if (key === 'id') {
        result.value = String(data[key])
      } else {
        result[key] = getGroupListTrees(data[key])
      }
    }
    return result
  } else {
    return data
  }
}
/** 查询部门列表 */
const getDepartList = async () => {
  const data = await DeptApi.getDeptTree()
  departList.value = getGroupListTrees(data.tree)
  departList1.value = getGroupListTrees(data.tree)
}

/** 查询角色列表 */
const getRoleList = async () => {
  const data = await RoleApi.getSimpleRoleList()
  data.map((v) => {
    v.id = String(v.id)
  })
  roleList.value = data
}
/** 查询岗位列表 */
const getPostList = async () => {
  const data = await PostApi.getSimplePostList()
  data.map((v) => {
    v.id = String(v.id)
  })
  postList.value = data
}
/** 查询行政列表 */
const getDutyList = async () => {
  const data = await Api.getJobPage()
  data.list.map((v) => {
    v.id = String(v.id)
  })
  dutyList.value = data.list
}
/** 查询工作组列表 */
const getWorkGroupList = async () => {
  const data = await Api.getWorkGroupPage()
  data.list.map((v) => {
    v.id = String(v.id)
  })
  workGroupList.value = data.list
}
/** 查询白名单列表 */
const getUserList = async () => {
  const data = await Api.searchAllMedicalUsers()
  let list: any = []
  data.MedicalUserList.map((v) => {
    list.push({
      name: v.name,
      id: String(v.id)
    })
  })
  whiteList.value = list
}
/** 打开弹窗 */
const open = async (id, basicId, isSingleConfig) => {
  dialogVisible.value = true
  // 修改时，设置数据
  if (id) {
    showSingle.value = isSingleConfig == '1'
    newBasicId = basicId
    newTechId = id
    getDepartList()
    getRoleList()
    getPostList()
    getDutyList()
    getWorkGroupList()
    getUserList()
    const params = {
      basicId: basicId,
      techId: id
    }
    const data = await Api.getAuthRuleByTechId(params)
    data.list.map((v) => {
      v.columnCheckFlag = v.columnCheckFlag == 1
      if (v.columnName !== 'sex' && v.columnName !== 'isAutoAuth') {
        v.columnValue = v.columnValue ? v.columnValue.split(',') : []
      }
      v.disabledRule = !v.columnCheckFlag
    })
    configList.value = cloneDeep(data.list)
    parentId.value = id
    getTechList('')
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const handleRule = async (id) => {
  selectId.value = id
  const params = {
    basicId: newBasicId,
    techId: id
  }
  const data = await Api.getAuthRuleByTechId(params)
  data.list.map((v) => {
    v.columnCheckFlag = v.columnCheckFlag == 1
    if (v.columnName !== 'sex' && v.columnName !== 'isAutoAuth') {
      v.columnValue = v.columnValue ? v.columnValue.split(',') : []
    }
    v.disabledRule = !v.columnCheckFlag
  })
  itemConfigList.value = cloneDeep(data.list)
}

const getTechList = async (value) => {
  const params = {
    parentId: parentId.value,
    name: value
  }
  const res = await Api.getTechByParentId(params)
  techList.value = res.techList
  if (res.techList.length > 0) {
    selectId.value = techList.value[0].id
    handleRule(techList.value[0].id)
  }
}

const getName = (value) => {
  switch (value) {
    case 'sex':
      return '性别'
      break
    case 'departId':
      return '所属科室'
      break
    case 'bizDepartId':
      return '业务科室'
      break
    case 'roleId':
      return '角色'
      break
    case 'postId':
      return '岗位'
      break
    case 'dutyId':
      return '行政职务'
      break
    case 'workGroupId':
      return '工作组'
      break
    case 'whiteList':
      return '白名单'
      break
    case 'isAutoAuth':
      return '自动授权'
      break
  }
}

const handleChecked = (value, column, row) => {
  console.log(value)
  if (column && row) {
    row[column] = value
  }
}
const handleChecked1 = (value, column, row) => {
  if (column && row) {
    row[column] = value
  }
  techList.value.map((v) => {
    if (v.id === selectId.value) {
      v.configList = itemConfigList.value
    }
  })
}

const submitForm = async () => {
  let configData: any = cloneDeep(configList.value)
  let newConfig: any = []
  configData.map((v) => {
    v.columnCheckFlag = v.columnCheckFlag ? 1 : 0
    if (v.columnName !== 'sex' && v.columnName !== 'isAutoAuth') {
      v.columnValue = v.columnValue.join(',')
    }
    let param = {
      columnName: v.columnName,
      columnValue: v.columnValue,
      columnCheckFlag: v.columnCheckFlag,
      id: v.id ? v.id : undefined
    }
    newConfig.push(param)
  })
  let params: any = {
    basicId: newBasicId,
    typeConfigList: newConfig,
    basicTechId: newTechId,
    isSingleConfig: showSingle.value ? '1' : '0'
  }
  if (showSingle.value) {
    let singleList: any = []
    let singleTechList = cloneDeep(techList.value)
    singleTechList.map((v) => {
      if (v.configList) {
        v.configList.map((k) => {
          k.columnCheckFlag = k.columnCheckFlag ? 1 : 0
          if (k.columnName !== 'sex' && k.columnName !== 'isAutoAuth') {
            k.columnValue = k.columnValue.join(',')
          }
          let param: any = {
            techId: v.id,
            columnName: k.columnName,
            columnValue: k.columnValue,
            columnCheckFlag: k.columnCheckFlag,
            id: k.id ? k.id : undefined
          }
          singleList.push(param)
        })
      }
    })
    params.singleConfigList = singleList
  }
  await Api.saveTechAuthRule(params)
  message.success('保存成功')
  dialogVisible.value = false
  emit('success', true)
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
</script>
<style lang="scss" scoped>
.cardHeight {
  width: 100%;
  max-height: 400px;
  overflow-y: scroll;
}
.item:hover,
.active {
  color: #fff;
  background: #0097e0;
  cursor: pointer;
}
.techList {
  border: 1px solid #ebeef5;
  height: 445px;
  max-height: 445px;
  overflow-y: auto;
}
</style>
